﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.IO;

namespace CommunitySystem.PageView.晋升管理
{
    public partial class PromotCheckWindow : ChildWindow
    {
        private JinShengService.JinShen_MainInfo _mainInfo = null;
        private PublicOfficialSelectionService.PublicOfficialSelectionServiceClient downLoadClient = null;
        List<byte> fileContent = new List<byte>();
        private JinShengService.JinShen_MainInfo_Check checkEntity = null;
        private JinShengService.JinShengServiceClient jinShenClient = null;
        public PromotCheckWindow(JinShengService.JinShen_MainInfo mainInfo)
        {
            InitializeComponent();
            _mainInfo = mainInfo;
            jinShenClient = new JinShengService.JinShengServiceClient();
            
            downLoadClient = new PublicOfficialSelectionService.PublicOfficialSelectionServiceClient();
            downLoadClient.DownLoadFileCompleted += (sender, e) =>
            {
                var down = e.Result;
                fileContent.AddRange(down.Content);
                if (down.HasFinished == true)
                {
                    var stream = e.UserState as Stream;
                    stream.Write(fileContent.ToArray(), 0, fileContent.Count);
                    stream.Dispose();
                    stream.Close();
                    SilverlightMessageBoxLibrary.Message.InfoMessage("下载完毕!");
                }
                else
                {
                    down.StartPosition += down.Lenght;
                    downLoadClient.DownLoadFileAsync(down, e.UserState);
                }
            };
           
            ///前面是方案审核，后面是候选人审核
            if (_mainInfo.Status == JinShenConst.STATUS_Solution_Submit || _mainInfo.Status == JinShenConst.STATUS_CandidateChecking)//新增一条审核信息
            {
                checkEntity = new JinShengService.JinShen_MainInfo_Check() { MainID = mainInfo.ID };
                DataBinding();
            }
            else//编辑一条审核信息
            {
                jinShenClient.GetMainInfo_CheckCompleted += (sender, e) =>
                {
                    checkEntity = e.Result.FirstOrDefault();
                    DataBinding();
                };
                jinShenClient.GetMainInfo_CheckAsync("MainID=" + mainInfo.ID + "  order by id desc");
            }


            jinShenClient.SaveJinShenMainInfoCompleted += (sender, e) =>
            {
                if (e.Error == null)
                {
                    
                    jinShenClient.SaveMainInfo_CheckAsync(checkEntity);
                }
                else
                {
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("保存失败");
                }
            };
            jinShenClient.SaveMainInfo_CheckCompleted += (sender1, e1) =>
            {
                if (e1.Error == null && e1.Result == true)
                {
                    SilverlightMessageBoxLibrary.Message.InfoMessage("保存成功");
                    this.DialogResult = true;
                }
                else
                {
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("保存失败");
                }
            };
            
        }

        private void DataBinding()
        {
            
            mainInfoGrid.DataContext = _mainInfo;
            dcbPromotionType.SelectedValue = _mainInfo.PromotType;
            //if (_mainInfo.PromotType.Equals("竞争上岗"))
            //{
                hlb.Visibility = System.Windows.Visibility.Visible;
                wp.Visibility = System.Windows.Visibility.Visible;
                foreach (var attach in _mainInfo.Attachment)
                {
                    StackPanel sp = new StackPanel() { Orientation = Orientation.Horizontal, };
                    HyperlinkButton hlbFile = new HyperlinkButton() { Content = attach.realname, DataContext = attach };
                    sp.Children.Add(hlbFile);
                    hlbFile.Click += (sender, e) =>
                    {
                        string extend =  attach.realname.Split('.').LastOrDefault();
                        var openFile = new SaveFileDialog() { Filter = string.Format("{0}|*.{0}", extend) };
                        if (openFile.ShowDialog() == true)
                        {
                            fileContent.Clear();
                            downLoadClient.DownLoadFileAsync(new PublicOfficialSelectionService.DownLoadFile()
                            { PathKey = "file", HasFinished = false, Lenght = 1600, FileName = attach.filename, StartPosition = 0 }, openFile.OpenFile());
                        }
                    };
                    wp.Children.Add(sp);
                }
            //}
            //else
            //{
            //    hlb.Visibility = System.Windows.Visibility.Collapsed;
            //    wp.Visibility = System.Windows.Visibility.Collapsed;
            //}
            if (checkEntity.IsPass == true)
            {
                dcbAgree.SelectedValue = "同意";
            }
            else if (checkEntity.IsPass == false)
            {
                dcbAgree.SelectedValue = "不同意";
            }
            if (_mainInfo.Status == JinShenConst.STATUS_CandidateCheck_UnPass || _mainInfo.Status == JinShenConst.STATUS_CandidateCheck_Pass || _mainInfo.Status == JinShenConst.STATUS_CandidateChecking)
            {
                mainInfoGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(), MaxHeight = 120 });
                ListBox lb = new ListBox() { Height = 120, Margin = new Thickness(8, 30, 0, 0), DisplayMemberPath = "Name" };
                Grid.SetRow(lb, 5);
                Grid.SetColumn(lb, 1);
                Grid.SetColumnSpan(lb, 2);
                lb.ItemsSource = _mainInfo.Details;
                this.Title = "人员审核";
                mainInfoGrid.Height += 140;
                mainInfoGrid.Children.Add(lb);
            }
            tbDSC.DataContext = checkEntity;
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            if (Validate())
            {
                if (checkEntity.IsPass == false)
                    _mainInfo.DSC = checkEntity.DSC;
                else
                    _mainInfo.DSC = "";

                if (_mainInfo.Status == JinShenConst.STATUS_CandidateCheck_UnPass || _mainInfo.Status == JinShenConst.STATUS_CandidateCheck_Pass || _mainInfo.Status == JinShenConst.STATUS_CandidateChecking)
                {
                    if (checkEntity.IsPass == true)
                    {
                        _mainInfo.Status = JinShenConst.STATUS_CandidateCheck_Pass;
                    }
                    else if (checkEntity.IsPass == false)
                    {
                        _mainInfo.Status = JinShenConst.STATUS_CandidateCheck_UnPass;
                    }
                }
                else
                {
                    if (checkEntity.IsPass == true)
                    {
                        _mainInfo.Status = JinShenConst.STATUS_SolutionPass;
                    }
                    else if (checkEntity.IsPass == false)
                    {
                        _mainInfo.Status = JinShenConst.STATUS_Solution_Retire;
                    }
                }

               
                    
                jinShenClient.SaveJinShenMainInfoAsync(_mainInfo);
            }
            
        }

        private bool Validate()
        {
            if (checkEntity.IsPass == null)
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("请选择是否同意!");
                return false;
            }
            if (checkEntity.IsPass == false && string.IsNullOrEmpty(checkEntity.DSC))
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("请填写不同意理由!");
                return false;
            }

            //if (_mainInfo.Status == JinShenConst.STATUS_SolutionPass || _mainInfo.Status == JinShenConst.STATUS_CandidateCheck_UnPass)//方案审核通过 和人员审核不通过
            //{
            //    if (_mainInfo.PromotType == "竞争上岗")
            //    {
            //        if (_mainInfo.Details == null || _mainInfo.Details.Count <= 1)
            //        {
            //            SilverlightMessageBoxLibrary.Message.InfoMessage("竞争上岗至少有两位候选人!");
            //            return false;
            //        }
            //    }
            //    else
            //    {
            //        if (_mainInfo.Details == null || _mainInfo.Details.Count < 1)
            //        {
            //            SilverlightMessageBoxLibrary.Message.InfoMessage("竞争上岗至少有一位候选人!");
            //            return false;
            //        }
            //    }
            //}
            
            return true;
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void dcbAgree_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (dcbAgree.SelectedValue != null && dcbAgree.SelectedValue.ToString().Equals("同意"))
            {
                checkEntity.IsPass = true;
                //checkEntity.DSC = "";
            }
            else if (dcbAgree.SelectedValue != null && dcbAgree.SelectedValue.ToString().Equals("不同意"))
            {
                checkEntity.IsPass = false;
            }

            if (checkEntity.IsPass == true)
            {
                //tbDSC.IsReadOnly = true;
            }
            else if (checkEntity.IsPass == false)
            {
               // tbDSC.IsReadOnly = false;
            }
        }
    }
}

